package com.leet.map;

import java.util.HashMap;
import java.util.HashSet;

public class LRUCache {
    private HashMap<Integer,Node> map;
    private DoubleList doubleList;
    private int capacity;

    public LRUCache(int capacity){
        this.capacity = capacity;
        map = new HashMap<>();
        doubleList = new DoubleList();

    }
    public int get(int key) {
        if(!map.containsKey(key)){
            return -1;
        }
        // 利用put把它提前
        int val = map.get(key).val;
        put(key,val);
        return val;
    }

    public void put(int key, int value) {
        Node x = new Node(key,value);
        // 如果已经包含
        if(map.containsKey(key)){
            doubleList.remove(map.get(key));
            doubleList.addFirst(x);
            // 更新map中的数据
        }else{
            if(capacity == doubleList.size()){
                Node last = doubleList.removeLast();
                map.remove(last.key);
            }
            doubleList.addFirst(x);
            map.put(key,x);
        }


    }

}
